using System;
using System.Collections.Generic;
using System.Linq;
using Engine;

namespace RuthlessConquest {
    public static class EnumUtils {
        public struct NamesValues {
            public ReadOnlyList<string> Names;

            public ReadOnlyList<int> Values;
        }

        public static class Cache {
            public static Dictionary<Type, NamesValues> m_namesValuesByType = new();

            public static NamesValues Query(Type type) {
                lock (m_namesValuesByType) {
                    if (!m_namesValuesByType.TryGetValue(type, out NamesValues value)) {
                        NamesValues namesValues = default;
                        namesValues.Names = new ReadOnlyList<string>(new List<string>(Enum.GetNames(type)));
                        namesValues.Values = new ReadOnlyList<int>(new List<int>(Enum.GetValues(type).Cast<int>()));
                        value = namesValues;
                        m_namesValuesByType.Add(type, value);
                    }
                    return value;
                }
            }
        }

        public static string GetEnumName(Type type, int value) {
            int num = GetEnumValues(type).IndexOf(value);
            if (num >= 0) {
                return GetEnumNames(type)[num];
            }
            return "<invalid enum>";
        }

        public static ReadOnlyList<string> GetEnumNames(Type type) => Cache.Query(type).Names;

        public static ReadOnlyList<int> GetEnumValues(Type type) => Cache.Query(type).Values;
    }
}